package Chart_room;

import java.io.*;
import java.net.*;
import java.awt.event.*;
import java.awt.*;

import javax.swing.*;

public class Chat_room implements Runnable, ActionListener {
	JTextArea showArea;
	JLabel lbl1, lbl2, lbl3;
	// 消息,发送端口号,接收端口号,对方ip地址
	JTextField msgText, sendPortText, receivePortText, IPAddressText;
	JFrame mainJframe;
	JButton sendBtn, startBtn;
	JScrollPane JSPane;
	JPanel pane1, pane2;
	Container con;
	Thread thread = null;
	// DatagramPacket,DatagramSocket，这两个类所有构成的网络链接是基于UDP协议
	DatagramPacket sendPack, receivePack;
	DatagramSocket sendSocket, receiveSocket;
	private InetAddress sendIP;
	private int sendPort, receivePort; // 存储发送端口和接收端口
	private byte inBuf[], outBuf[];
	public static final int BUFSIZE = 1024;

	public Chat_room() {

		// java swing 界面构造
		mainJframe = new JFrame("UDP,多线程聊天室");
		con = mainJframe.getContentPane();
		showArea = new JTextArea();
		showArea.setEditable(false);
		showArea.setLineWrap(true);
		lbl1 = new JLabel("接收端口号:");
		lbl2 = new JLabel("发送端口号:");
		lbl3 = new JLabel("对方地址:");
		sendPortText = new JTextField();
		sendPortText.setColumns(5);
		receivePortText = new JTextField();
		receivePortText.setColumns(5);
		IPAddressText = new JTextField();
		IPAddressText.setColumns(8);
		startBtn = new JButton("运行");
		startBtn.addActionListener(this);
		pane1 = new JPanel();
		pane1.setLayout(new FlowLayout());
		pane1.add(lbl1);
		pane1.add(receivePortText);
		pane1.add(lbl2);
		pane1.add(sendPortText);
		pane1.add(lbl3);
		pane1.add(IPAddressText);
		pane1.add(startBtn);
		JSPane = new JScrollPane(showArea);
		msgText = new JTextField();
		msgText.setColumns(40);
		msgText.setEditable(false);
		msgText.addActionListener(this);
		sendBtn = new JButton("发送");
		sendBtn.setEnabled(false);
		sendBtn.addActionListener(this);
		pane2 = new JPanel();
		pane2.setLayout(new FlowLayout());
		pane2.add(msgText);
		pane2.add(sendBtn);
		con.add(pane1, BorderLayout.NORTH);
		con.add(JSPane, BorderLayout.CENTER);
		con.add(pane2, BorderLayout.SOUTH);
		mainJframe.setSize(600, 400);
		mainJframe.setVisible(true);
		mainJframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void actionPerformed(ActionEvent e) {
		try {
			if (e.getSource() == startBtn) { // 按下运行按钮
				if (sendPortText.getText().toString().equals(""))
					JOptionPane.showMessageDialog(startBtn, "请输入发送端口号！！！");
				else if (receivePortText.getText().toString().equals(""))
					JOptionPane.showMessageDialog(startBtn, "请输入接受端口号！！！");
				else {/* 构造发送端socket */
					sendPort = Integer.parseInt(sendPortText.getText());
					sendIP = InetAddress.getByName(IPAddressText.getText());
					sendSocket = new DatagramSocket();

					/* 构造接收端socket */
					receivePort = Integer.parseInt(receivePortText.getText());
					// 创建接收数据包
					inBuf = new byte[BUFSIZE];
					receivePack = new DatagramPacket(inBuf, BUFSIZE);
					// 指定接收数据的端口
					receiveSocket = new DatagramSocket(receivePort);

					/* 创建线程准备接收对方的消息 */
					thread = new Thread(this);
					thread.setPriority(Thread.MIN_PRIORITY);
					thread.start();

					startBtn.setEnabled(false);
					sendBtn.setEnabled(true);
					msgText.setEditable(true);
				}
			} else { // 按下了发送按钮或回车键
				outBuf = msgText.getText().getBytes();
				// 组装要发送的数据包
				sendPack = new DatagramPacket(outBuf, outBuf.length, sendIP,
						sendPort);
				// 发送数据
				sendSocket.send(sendPack);
				showArea.append("我：" + msgText.getText() + "\n");
				msgText.setText(null);
			}
		} catch (UnknownHostException el) {
			showArea.append("无法连接到指定地址\n");
		} catch (SocketException el) {
			showArea.append("无法打开指定端口\n");
		} catch (IOException el) {
			showArea.append("发送数据失败\n");
		}
	}

	// 在线程中接收数据
	public void run() {
		String msgstr;
		while (true) {
			try { // 注意这个try的位置
				receiveSocket.receive(receivePack);
				msgstr = new String(receivePack.getData(), 0,
						receivePack.getLength());
				showArea.append("朋友：" + msgstr + "\n");
			} catch (IOException el) {
				showArea.append("接收数据出错\n");
			}
		}
	}

	public static void main(String[] args) {
		new Chat_room();
	}
}